package cn.edu.sdjzu.cs.dingcan.service;

import cn.edu.sdjzu.cs.dingcan.dao.CustomerDao;
import cn.edu.sdjzu.cs.dingcan.entity.Customer;
import org.mindrot.jbcrypt.BCrypt;

import javax.servlet.http.HttpSession;
import java.sql.SQLException;

public class CustomerService {
    private final CustomerDao customerDao;

    public CustomerService() {
        this.customerDao = new CustomerDao();
    }

    public void customerRegister(String username, String realName, String phoneNumber, String email, String deliveryAddress,
                             String password) throws SQLException {
        Customer customer = new Customer();
        customer.setUsername(username);
        customer.setRealName(realName);
        customer.setPhoneNumber(phoneNumber);
        customer.setEmail(email);
        customer.setDeliveryAddress(deliveryAddress);
        customer.setStatus(Customer.CustomerStatus.Enabled);
        // 计算密码HASH
        String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
        customer.setPassword(hashed);

        this.customerDao.add(customer);
    }

    public boolean login(String username, String password, HttpSession session) throws SQLException {
        Customer customer = this.customerDao.getCustomer(username);
        if(customer == null) {  // 根据用户名未找到用户
            return false;
        }
         if (BCrypt.checkpw(password, customer.getPassword())) {
            // 不在对象中保存密码
            customer.setPassword(null);
            // 将customer对象放入session
            session.setAttribute("customer", customer);
            // 更新最后登录时间
            this.customerDao.updateLastLoginTime(username);
            return true;
        } else {
            return false;
        }
    }

    public boolean usernameExist(String username) throws SQLException {
        return this.customerDao.getCustomer(username) != null;
    }

    public Customer getCustomerById(Long customerId) throws SQLException {
        return this.customerDao.getCustomer(customerId);
    }
}
